/*******************************************************************************
 * CopyRight (c) 2020 
 *
 * \file    io_file.c
 * \brief   get format file
 * \author  ZhangJing
 * \version 1.0.0
 * \date    2020-07-08
 *
 * -----------------------------------------------------------------------------
 * Modified history：
 * <Date>       | <Version> | <Author>  | <Describe>
 * 2020-07-08   | v1.0.0    | ZhangJing | Create file
 * -----------------------------------------------------------------------------
 ******************************************************************************/

#include <stdio.h>

#include "publicdef.h"
#include "print_ctrl.h"
#include "format.h"

int file_io_open(struct IOContext *h, const char *name, char *flags)
{
    h->fh = fopen(name, flags);
    if (!h->fh) {
        pr_err("file %s open fail!", name);
        return -ENOENT;
    }

    h->filename = name;

    pr_info("file %s opened", name);
}

int file_io_read(struct IOContext *h, void *buf, unsigned int size)
{
    return fread(buf, 1, size, h->fh);
}

int file_io_write(struct IOContext *h, const unsigned char *buf, int size)
{
    return fwrite(buf, 1, size, h->fh);
}

long file_io_seek(struct IOContext *h, long pos, int whence)
{
    return fseek(h->fh, pos, whence);
}
int file_io_close(struct IOContext *h)
{
    return fclose(h->fh);
}

long file_io_get_len(struct IOContext *h)
{
    long len;

    fseek(h->fh, 0L, SEEK_END);
    len = ftell(h->fh);
    fseek(h->fh, 0L, SEEK_SET);

    return len;
}

long file_io_tell(struct IOContext *h)
{
    return ftell(h->fh);
}

IOContext io_file = {
    NULL, NULL, 0, NULL, NULL, 0, 0,
    0, NULL,
    file_io_open, file_io_read, file_io_write,
    file_io_seek, file_io_close, file_io_get_len, file_io_tell
};
